/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.util.files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import ventasdia.Variables;

/**
 *
 * @author Usuario
 */
public class Ficheros {

    private static final String RUTA = "ventasdia.ini";

    public static void leer() {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(RUTA)));
            Variables.rutaBitronik = in.readLine();
            Variables.rutaRespaldo = in.readLine();
            Variables.rutaBaseDatosTrabajo = in.readLine();
            Variables.respaldo = Boolean.parseBoolean(in.readLine());
            Variables.ticket = Boolean.parseBoolean(in.readLine());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }

    public static void escribir() {

        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(RUTA)));


            out.write(Variables.rutaBitronik);
            out.write("\n");
            out.write(Variables.rutaRespaldo);
            out.write("\n");
            out.write(Variables.rutaBaseDatosTrabajo);
            out.write("\n");
            out.write(Boolean.toString(Variables.respaldo));
            out.write("\n");
            out.write(Boolean.toString(Variables.ticket));
            out.write("\n");


        } catch (IOException e) {
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
            }
        }
    }

    public static boolean existeFicheroConfiguracion() {
        File fichero = new File(RUTA);
        return fichero.exists();
    }

    public static void mover(String rutaOrigen, String rutaDestino) {
        try {
            File ficheroOriginal = new File(rutaOrigen);
            File ficheroNuevo = new File(rutaDestino);
            copyFile(ficheroOriginal, ficheroNuevo);
        } catch (IOException ex) {
            Logger.getLogger(Ficheros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void copyFile(File in, File out)
            throws IOException {

        FileChannel inChannel = new FileInputStream(in).getChannel();

        FileChannel outChannel = new FileOutputStream(out).getChannel();

        try {

            inChannel.transferTo(0, inChannel.size(),
                    outChannel);

        } catch (IOException e) {

            throw e;

        } finally {

            if (inChannel != null) {
                inChannel.close();
            }

            if (outChannel != null) {
                outChannel.close();
            }

        }

    }

    public static boolean descargarFichero(String direccion, String rutaDescarga) {
        boolean descargado = false;
        try {
            URL url = new URL(direccion);
            URLConnection urlCon = url.openConnection();

            // acceso al contenido web
            InputStream is = urlCon.getInputStream();

            // Fichero en el que queremos guardar el contenido
            FileOutputStream fos = new FileOutputStream(rutaDescarga);

            // buffer para ir leyendo.
            byte[] array = new byte[1000];

            // Primera lectura y bucle hasta el final
            int leido = is.read(array);
            while (leido > 0) {
                fos.write(array, 0, leido);
                leido = is.read(array);
            }
            descargado = true;
            // Cierre de conexion y fichero.
            is.close();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();

        }
        return descargado;
    }

    public static void descomprimirFichero(String rutaFichero) {

        RandomAccessFile randomAccessFile = null;
        ISevenZipInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(rutaFichero, "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

            // Getting simple interface of the archive inArchive
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

            System.out.println("   Hash   |    Size    | Filename");
            System.out.println("----------+------------+---------");

            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                final int[] hash = new int[]{0};
                if (!item.isFolder()) {
                    ExtractOperationResult result;
                    File f = new File(item.getPath());
                    final FileOutputStream out = new FileOutputStream(Variables.d_actualizacion+"\\"+f);
                    final long[] sizeArray = new long[1];
                    result = item.extractSlow(new ISequentialOutStream() {

                        public int write(byte[] data) throws SevenZipException {
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            try {
                                out.write(data);
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                            return data.length; // Return amount of consumed data

                        }
                    });
                    out.close();
                    if (result == ExtractOperationResult.OK) {
                        System.out.println(String.format("%9X | %10s | %s", // 
                                hash[0], sizeArray[0], item.getPath()));
                    } else {
                        System.err.println("Error extracting item: " + result);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
            System.exit(1);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }

    public static void escribir_fichero_texto(String nombre, StringBuffer contenido) {
        File f;
        f = new File(nombre);

        try {
            FileWriter w = new FileWriter(f);
            BufferedWriter bw = new BufferedWriter(w);
            PrintWriter wr = new PrintWriter(bw);
            wr.write(contenido.toString());
            wr.close();
            bw.close();
        } catch (IOException e) {
        };

    }

    public static InputStream leer_fichero_texto(String nombre) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(nombre);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
       
        return inputStream;
    }
}
